package basic.study.leetcode;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Mid227 {
    public static  void main (String[] args) {
        System.out.println(calculate(" 3+5 / 2 +1"));
    }

    public static int calculate(String s) {
        int res=0,cur;
        Stack<String> stack = new Stack<>();
        Queue<String> queue = new LinkedList<>();

        for(int i=0; i < s.length(); i++) {
            String ss = String.valueOf(s.charAt(i));
            if(ss.equals(" ")) {
                continue;
            }else if(ss.equals("*")|| ss.equals("/")) {

                //如果有同级的
                while(!stack.empty() && (stack.peek().equals("*") ||stack.peek().equals("/") )) {
                    queue.offer(stack.pop());
                }
                stack.push(ss);
            }else if(ss.equals("+")|| ss.equals("-")) {

                while(!stack.empty()) {
                    queue.offer(stack.pop());
                }
                stack.push(ss);
            } else {
                cur = s.charAt(i) - '0';
                while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {
                    cur = cur * 10 + s.charAt(++i) - '0';
                }
                queue.offer(String.valueOf(cur));
            }
        }
        while(!stack.isEmpty()) queue.offer(stack.pop());
        //System.out.println(queue.toString());

        //逆波兰求解
        Stack<Integer> stack1 = new Stack<>();
        while(!queue.isEmpty()) {
            String op = queue.poll();
            if(Character.isDigit(op.charAt(0))) {
                stack1.push(Integer.valueOf(op));
            }else {
                stack1.push(ops(op,stack1.pop(), stack1.pop()));
            }
        }

        return stack1.pop();
    }

    public static int ops(String op, int i1, int i2) {
        int res = 0;
        switch (op) {
            case "+": res = i1 + i2;break;
            case "-": res = -i1 + i2;break;
            case "*": res = i1 * i2;break;
            case "/": res = i2 / i1;break;
        }
        return res;
    }

}
